package bstsetcode;

import java.lang.reflect.Method;

/**
 * @author noob
 * @version 1.0
 * @date 2021/3/13 20:01
 */
public class SortHelper {

    public SortHelper() {
    }

    /**
     * 判断数组是不是有序
     * @param arr 数组
     * @param <E> 泛型
     * @return  布尔值，false表示无序
     */
    public static <E extends Comparable<E>> boolean isSorted(E[] arr){

        for (int i = 1; i < arr.length; i++) {
            if(arr[i-1].compareTo(arr[i])> 0){
                return false;
            }
        }
        return true;
    }



    public static <E extends Comparable<E>> void sortTest(String sortName,E[] arr){
        long startTime = System.nanoTime();
        if("InsertionSortT".equals(sortName)){
            InsertionSortT.sort(arr);
        }else if("InsertionSortT2".equals(sortName)){
            InsertionSortT2.sort(arr);
        }


        long endTime = System.nanoTime();
        double  time = (endTime - startTime)/1000000000.0;
        if(!SortHelper.isSorted(arr)){
            throw  new RuntimeException( sortName + "failed");
        }
        System.out.println(String.format("%s , n = %d: %f s",sortName,arr.length,time));
    }

    /**
     * 通过反射机制，测试排序算法
     * @param sortName  需要加载包名
     * @param arr
     * @param <E>
     *     eg:SortHelper.sortTestReflect("code.SelectionSortT",arr);
     */
    public static <E extends Comparable<E>> void sortTestReflect(String sortName,E[] arr){
        try {
            Class sortClass = Class.forName(sortName);
            Method sortMethod = sortClass.getMethod("sort",Comparable[].class);
            Object[] params = new Object[]{arr};

            long startTime = System.nanoTime();
            sortMethod.invoke(null,params);
            long endTime = System.nanoTime();
            double  time = (endTime - startTime)/1000000000.0;
            if(!SortHelper.isSorted(arr)){
                throw  new RuntimeException( sortName + "failed");
            }
            System.out.println(String.format("%s , n = %d: %f s",sortName,arr.length,time));


        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            System.out.println("Error in SortHelper.sortTestReflect");
        }

    }

}
